package com.hunanwenli.mq;
import com.alibaba.fastjson.JSON;
import com.hunanwenli.entity.OrderMsg;
import com.hunanwenli.entity.OrderStatus;
import com.hunanwenli.mapper.OrderMsgMapper;
import com.hunanwenli.mapper.OrderStatusMapper;
import com.hunanwenli.mapper.ShopGoodsMapper;
import com.hunanwenli.service.RedisService;
import com.rabbitmq.client.Channel;
import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @author wanzhenyu
 * @date 2021/6/6 10:40
 */
@Service
@Log4j2
public class OrderMqConsumer {
    @Autowired
    private OrderMsgMapper orderMsgMapper;
    @Autowired
    private RedisService redisService;
    @Autowired
    private ShopGoodsMapper shopGoodsMapper;
    @Autowired
    private OrderStatusMapper orderStatusMapper;
    @RabbitListener(queues = {"seckillQueue"})
    @Transactional(rollbackFor = {Exception.class})
    public void messageConsumer(String ordermsg, Channel channel,
                                CorrelationData correlationData,
                                @Header(AmqpHeaders.DELIVERY_TAG) Long tag)throws Exception{
      try {
          //手动应答处理异常 try catch
          OrderMsg order = JSON.parseObject(ordermsg, OrderMsg.class);
          //发生异常
          //System.out.println(1/0);
          String key = order.getId();
          if (redisService.hasKey(key)){
             throw  new RuntimeException("订单以已存在");
          }
          //插入订单
          int insert = orderMsgMapper.insert(order);
          //修改库存
          int update = shopGoodsMapper.updateInventoryDecrement(order.getSeckillId());

          if (insert==1&&update==1){
              //未发生异常，执行完毕，自动应答
              redisService.put(key,"key",500L);
              channel.basicAck(tag,false);
          }else {
              log.error("订单异常"+order.getId()+" insert==="+insert+"  i==="+update);
              throw new RuntimeException("订单异常"+order.getId()+" insert==="+insert+"  i==="+update);
          }
      }catch (Exception e){
          //不重发 手动应答
          channel.basicNack(tag,false,false);
      }
    }
}
